import 'package:flutter/material.dart';
import '../models/product_model.dart';
import '../services/product_service.dart';
import '../models/product_detail_model.dart';

class ProductProvider with ChangeNotifier {
  final ProductService _productService;
  // 添加模拟数据开关
  bool _useMockData = true; // 设置为true使用模拟数据

  List<Product> _products = [];
  bool _isLoading = false;
  String _errorMessage = '';
  Product? _selectedProduct;

  ProductProvider(this._productService);

  // Getters
  List<Product> get products => _products;
  bool get isLoading => _isLoading;
  String get errorMessage => _errorMessage;
  Product? get selectedProduct => _selectedProduct;

  // 获取商品列表
  Future<void> fetchProducts({String? categoryId}) async {
    _isLoading = true;
    notifyListeners();

    try {
      _products = await _productService.getProducts(categoryId: categoryId);
      _errorMessage = '';
    } catch (e) {
      _errorMessage = '获取商品列表失败: $e';
      _products = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 获取商品详情
  Future<void> fetchProductDetail1(String productId) async {
    _isLoading = true;
    notifyListeners();

    try {
      _selectedProduct = await _productService.getProductDetail1(productId);
      _errorMessage = '';
    } catch (e) {
      _errorMessage = '获取商品详情失败: $e';
      _selectedProduct = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 搜索商品
  Future<void> searchProducts(String query) async {
    _isLoading = true;
    notifyListeners();

    try {
      _products = await _productService.searchProducts(query);
      _errorMessage = '';
    } catch (e) {
      _errorMessage = '搜索商品失败: $e';
      _products = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  ProductDetail? _productDetail;
  ProductDetail? get productDetail => _productDetail;

  Future<void> fetchProductDetail(String productId) async {
    _isLoading = true;
    _errorMessage = '';
    notifyListeners();

    try {
      if (_useMockData) {
        // 模拟数据
        await Future.delayed(Duration(milliseconds: 500)); // 模拟网络延迟
        _productDetail = ProductDetail(
          id: productId,
          name: '模拟商品名称',
          description: '这是一个模拟的商品详情描述，包含商品的各种信息。',
          price: 99.99,
          originalPrice: 129.99,
          images: [
            'https://ts2.tc.mm.bing.net/th/id/OIP-C.MtG5BHWcXTADVW7trlPvpAHaEJ?cb=thfvnext&rs=1&pid=ImgDetMain&o=7&rm=3',
            'https://ts2.tc.mm.bing.net/th/id/OIP-C.MtG5BHWcXTADVW7trlPvpAHaEJ?cb=thfvnext&rs=1&pid=ImgDetMain&o=7&rm=3',
          ],
          specs: [
            ProductSpec(
              name: '颜色',
              values: ['红色', '蓝色', '黑色'],
              selectedValue: '红色',
            ),
            ProductSpec(
              name: '尺寸',
              values: ['S', 'M', 'L'],
              selectedValue: 'M',
            ),
          ],
          stock: 100,
          rating: 4.8,
          reviewCount: 120,
          tags: ['热门', '新品'],
        );
        notifyListeners();
      } else {
        // 真实接口调用
        _productDetail = await _productService.getProductDetail(productId);
        notifyListeners();
      }
    } catch (e) {
      _errorMessage = '获取商品详情失败: $e';
      rethrow;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  void updateSelectedSpec(int specIndex, String value) {
    if (_productDetail == null) return;

    final updatedSpecs = _productDetail!.specs.map((spec) => spec).toList();
    updatedSpecs[specIndex] = updatedSpecs[specIndex].copyWith(
      selectedValue: value,
    );

    _productDetail = _productDetail!.copyWith(specs: updatedSpecs);
    notifyListeners();
  }
}

extension ProductDetailExtension on ProductDetail {
  ProductDetail copyWith({List<ProductSpec>? specs}) {
    return ProductDetail(
      id: id,
      name: name,
      description: description,
      price: price,
      originalPrice: originalPrice,
      images: images,
      specs: specs ?? this.specs,
      stock: stock,
      rating: rating,
      reviewCount: reviewCount,
      tags: tags,
    );
  }
}
